package com.ctsi.system.app.rest;

import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.request.UtilHttp;
import com.ctsi.commons.util.response.Page;
import com.ctsi.framework.common.constant.ResponseCodeEnum;
import com.ctsi.framework.common.response.UnifiedResponse;
import com.ctsi.framework.common.response.UnifyResponse;
import com.ctsi.framework.elementui.support.Option;
import com.ctsi.system.domain.Dictionary;
import com.ctsi.system.domain.DictionaryData;
import com.ctsi.system.service.DictionaryDataService;
import com.ctsi.system.service.DictionaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zhangjw
 *
 * 字典服务类
 */
@RestController
@RequestMapping("/dict")
public class DictionaryController {

    private static final Logger logger = LoggerFactory.getLogger(DictionaryController.class);

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private DictionaryDataService dictionaryDataService;

    @GetMapping(value = "/dictTypePage",produces = "application/json")
    public UnifyResponse<Page<Dictionary>> queryPage(@RequestParam Map<String, Object> params,
                                                     @RequestParam(defaultValue = Page.DEFAULT_PAGESIZE) Integer pageSize, @RequestParam Integer start){
        Map<String,Object> param = UtilHttp.filterBlank(params);
        Page<Dictionary> page = this.dictionaryService.findByMulitCondition(param,start,pageSize);
        return UnifyResponse.success(page);
    }

    @GetMapping(value = "/dictDataPage",produces = "application/json")
    public UnifyResponse<Page<DictionaryData>> queryData(@RequestParam Map<String, Object> params,
                                                         @RequestParam(defaultValue = Page.DEFAULT_PAGESIZE) Integer pageSize, @RequestParam Integer start){
        Map<String,Object> param = UtilHttp.filterBlank(params);
        Page<DictionaryData> page = this.dictionaryDataService.findByMulitCondition(param,start,pageSize);
        return UnifyResponse.success(page);
    }

    @GetMapping(value = "/get/{id}")
    @ResponseStatus(value = HttpStatus.OK)
    public UnifiedResponse<Dictionary> query(@PathVariable String id){
        Dictionary dict = this.dictionaryService.editDictionaryById(id);
        return UnifiedResponse.ok(dict);
    }

    @GetMapping(value = "/getData/{id}")
    @ResponseStatus(value = HttpStatus.OK)
    public UnifiedResponse<DictionaryData> queryData(@PathVariable String id){
        DictionaryData dict = this.dictionaryDataService.editDictionaryDataById(id);
        return UnifiedResponse.ok(dict);
    }

    @PostMapping(value = "/addDictType",consumes = "application/json")
    @ResponseStatus(value = HttpStatus.OK)
    public UnifiedResponse<Void> addDictType(@RequestBody Dictionary dictionary) {
        this.dictionaryService.insertDictionary(dictionary);
        return UnifiedResponse.ok();
    }

    @PostMapping(value = "/addDictData",consumes = "application/json")
    public UnifyResponse<String> addDictData(@RequestBody DictionaryData data){
        this.dictionaryDataService.insertDictionaryData(data);
        return UnifyResponse.success("添加成功!");
    }

    /**
     * 彻底删除，单个删除
     * @param id
     * @return
     */
    @DeleteMapping(value = "/remove/{id}")
    public UnifyResponse<String> remove(@PathVariable String id) {
        this.dictionaryService.removeDictionary(id);
        return UnifyResponse.success("删除成功!");
    }

    /**
     * 彻底删除，可批量操作
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/removes")
    public UnifiedResponse<String> removes(@RequestParam("ids") String ids){
        if (UtilValidate.isNotEmpty(ids)) {
            List<String> arr = new ArrayList<>();
            if (!ids.contains(",")){
               arr.add(ids);
            } else {
                arr =  Arrays.asList(ids.split(","));
            }
            int result = arr.stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    return this.dictionaryService.removeDictionary(id);
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.size() >1){
                return UnifiedResponse.ok("选中"+arr.size()+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return  UnifiedResponse.ok("删除成功!");
    }

    @DeleteMapping(value = "/removeDatas")
    public UnifyResponse<String> removeDatas(@RequestParam("ids[]") List<String> ids){
        Optional<List<String>> arr = Optional.ofNullable(ids);
        if(arr.isPresent()){
            int result = arr.get().stream().parallel().filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    return this.dictionaryDataService.removeDictionaryData(id);
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.get().size() >1){
                return UnifyResponse.success("选中"+arr.get().size()+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifyResponse.success("删除成功!");
            }
        }else{
            return UnifyResponse.error(ResponseCodeEnum.GL99990100);
        }
    }

    /**
     * 标记删除还原，可以批量操作
     * @param ids
     * @return
     */
    @PostMapping(value = "/updateisdel")
    public UnifiedResponse<String> updateStatus(@RequestParam(value = "ids") String ids){
        if (UtilValidate.isNotEmpty(ids)) {
            String[] arr = ids.split(",");
            int result = Stream.of(arr).filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    Dictionary dict = new Dictionary();
                    dict.setId(id);
                    Dictionary dictionary = dictionaryService.selectDescById(dict.getId());
                    if(UtilValidate.isNotEmpty(dictionary.getDictDesc())){
                        Long o = (Long) dictionaryService.selectChildCount(dictionary.getDictDesc());
                        if (o==0){
                            dict.setIsdel(1);
                            return this.dictionaryService.updateDictionaryByPKSelective(dict);
                        }else {
                            return 0;
                        }
                    }else{
                        return 0;
                    }
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.length >1){
                return UnifiedResponse.ok("选中"+arr.length+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }


    @PostMapping(value = "/updateDatadel")
    public UnifiedResponse<String> updateDatadel(@RequestParam(value = "ids") String ids){
        if (UtilValidate.isNotEmpty(ids)) {
            String[] arr = ids.split(",");
            int result = Stream.of(arr).filter(id -> UtilValidate.isNotEmpty(id)).mapToInt(id -> {
                try {
                    DictionaryData dict = new DictionaryData();
                    dict.setId(id);
                    dict.setIsdel(1);
                    return this.dictionaryDataService.updateDictionaryDataByPKSelective(dict);
                }catch (Exception e){
                    logger.error("{}",e);
                    return 0;
                }
            }).sum();
            if(arr.length >1){
                return UnifiedResponse.ok("选中"+arr.length+"条数据，成功删除"+result+"条数据！");
            }else {
                return UnifiedResponse.ok("删除成功!");
            }
        }
        return UnifiedResponse.ok("删除成功!");
    }

    @PutMapping("/update")
    @ResponseStatus(value = HttpStatus.OK)
    public UnifiedResponse<Void> update(@RequestBody Dictionary dictionary){
        try {
            this.dictionaryService.updateDictionaryByPKSelective(dictionary);
        }catch (Exception e){
            logger.error("{}",e);
            return UnifiedResponse.error(ResponseCodeEnum.GL99990500.code(),e.getMessage());
        }
        return UnifiedResponse.ok();
    }

    @PutMapping("/updateData")
    @ResponseStatus(value = HttpStatus.OK)
    public UnifiedResponse<Void> updateData(@RequestBody DictionaryData data){
        this.dictionaryDataService.updateDictionaryDataByPKSelective(data);
        return UnifiedResponse.ok();
    }


//    功能权限中用到
    /**
     * 通过类型获取字典数据
     * @param type
     * @return
     */
    @GetMapping(value = "/getdatabytype/{type}")
    public UnifiedResponse<List<Option>> getDataByType(@PathVariable String type){
        List<DictionaryData> dds = this.dictionaryDataService.findDatasByType(type);
        List<Option> ops = dds.stream().map(dd -> {
            return new Option(dd.getCode(),dd.getDictdataValue());
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(ops);
    }

    /**
     * 通过类型获取字典数据
     * @param type
     * @return
     */
    @PostMapping(value = "/getdatabytype/{type}")
    public UnifiedResponse<List<Option>> getDataByTypePost(@PathVariable String type){
        List<DictionaryData> dds = this.dictionaryDataService.findDatasByType(type);
        List<Option> ops = dds.stream().map(dd -> {
            return new Option(dd.getCode(),dd.getDictdataValue());
        }).collect(Collectors.toList());
        return UnifiedResponse.ok(ops);
    }


}
